<template>
  <el-dialog
    v-drag-dialog
    class="sxTableExport"
    title="表格导出"
    :visible="visible"
    width="50%"
    :close-on-click-modal="false"
    @close="handleDialogClose"
  >
    <!-- <el-alert
      class="sxTableExport__alert"
      title="注：请勾选需要导出的字段。字段可拖拽排序"
      type="info"
      show-icon
      :closable="false"
    />-->
    <div class="sxTableExport__template">
      <div class="sxTableExport__template_items sxTableExport__selectGroup">
        <!-- <div v-if="isDataKeyArray" class="sxTableExport__selectGroup_pane">
          <label>导出模式</label>
          <el-select
            v-model="exportKey"
            :size="$store.getters.size"
            @change="handleChangeExportKey"
          >
            <el-option
              v-for="item in dataKey"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>-->
        <!-- <div class="sxTableExport__selectGroup_pane">
          <label>导出模版</label>
          <el-select
            v-model="selectTemplate"
            :size="$store.getters.size"
            @change="OnChangeTemplate"
          >
            <el-option-group label="官方模板">
              <el-option
                v-for="(template, idx) in renderTemplateList.internal"
                :key="idx"
                :label="template.label"
                :value="template.value"
              />
            </el-option-group>
            <el-option-group label="用户自定义">
              <el-option
                v-for="(template, idx) in renderTemplateList.custom"
                :key="idx"
                :label="template.label"
                :value="template.value"
              />
            </el-option-group>
          </el-select>
        </div>-->
      </div>
      <!-- <div class="sxTableExport__template_items">
        <el-autocomplete
          v-model="state"
          :size="$store.getters.size"
          clearable
          :fetch-suggestions="querySearch"
          placeholder="快速选择"
          :trigger-on-focus="false"
          @select="handleSelect"
        />
        <el-button
          class="sxTableExport__toolBtn"
          :size="$store.getters.size"
          type="warning"
          @click="handleReset"
        >
          重置
        </el-button>
        <el-button
          class="sxTableExport__toolBtn"
          :size="$store.getters.size"
          type="primary"
          @click="handleSelectAll"
        >
          {{ `全${allSelected ? '不' : '勾'}选` }}
        </el-button>
      </div>-->
    </div>
    <div class="sxTableExport__setting">
      <div>
        <el-checkbox v-model="isSelected">仅导出勾选</el-checkbox>
        <el-checkbox v-model="isPartial">仅导出本页数据</el-checkbox>
      </div>
      <el-input
        v-model="fileName"
        :size="$store.getters.size"
        placeholder="自定义文件名"
        style="width:150px"
        prefix-icon="el-icon-edit"
        clearable
      />
    </div>
    <draggable
      v-loading="loading"
      :list="columnList"
      :animation="200"
      class="sxTableExport__columnList"
      ghost-class="sxTableExport__columnPane-ghost"
    >
      <div
        v-for="(column, columnIdx) in columnList"
        :key="columnIdx"
        class="sxTableExport__columnPane"
        :class="{ 'sxTableExport__columnPane-active': column.Picked }"
      >
        <div class="sxTableExport__columnCard" @click="_onClickColumnCard(column)">
          <span>{{ column.ColName }}</span>
        </div>
        <label class="sxTableExport__icon" :class="{ 'sxTableExport__icon-active': column.Picked }">
          <i class="el-icon-check" />
        </label>
      </div>
    </draggable>

    <template v-slot:footer>
      <div class="sxTableExport__footer">
        <!-- <el-button
          type="warning"
          :size="$store.getters.size"
          icon="el-icon-folder-checked"
          @click="_handleSave"
        >
          保存并导出
        </el-button>-->
        <el-button
          type="primary"
          :size="$store.getters.size"
          icon="el-icon-download"
          @click="_handleExport"
        >导出文档</el-button>
      </div>
    </template>
    <el-dialog
      v-drag-dialog
      class="sxTableExport__saveTemplate"
      title="保存模板"
      width="400px"
      :visible.sync="innerVisible"
      append-to-body
    >
      <div class="sxTableExport__alert">
        <el-alert
          class="sxTableExport__alert"
          :title="
            `注：最多保存${overflowTemplateNum}个自定义模板，超过请选择要替换的模板`
          "
          type="info"
          show-icon
          :closable="false"
        />
      </div>
      <div class="sxTableExport__changeTemplate">
        <div class="sxTableExport__newTemplateInfo">
          <label>选择模板</label>
          <el-select
            v-model="needChangeTemplate"
            placeholder="选择要替换的模板"
            style="width:150px"
            :size="$store.getters.size"
            clearable
          >
            <el-option-group label="官方模板">
              <el-option
                v-for="(template, idx) in renderTemplateList.internal"
                :key="idx"
                disabled
                :label="template.label"
                :value="template.value"
              />
            </el-option-group>
            <el-option-group label="用户自定义">
              <el-option
                v-for="(template, idx) in renderTemplateList.custom"
                :key="idx"
                :label="template.label"
                :value="template.value"
              />
            </el-option-group>
          </el-select>
        </div>
        <div class="sxTableExport__newTemplateInfo">
          <label>新模板名</label>
          <el-input
            v-model="templateName"
            :size="$store.getters.size"
            style="width:150px"
            placeholder="新的模板名字"
          />
        </div>
      </div>
      <template v-slot:footer>
        <div class="sxTableExport__saveTemplate_footer">
          <el-button type="primary" :size="$store.getters.size" @click="changeTemplate">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script>
import Dayjs from "dayjs";
import draggable from "vuedraggable";
import { deepCopy, downloadFile } from "@Components/assets/js/common";
import isString from "lodash/isString";
import isPlainObject from "lodash/isPlainObject";
import PinyinMatch from "pinyin-match";
import { isNull } from "xe-utils";
// import {
//   GetExportFeilds,
//   ExportExcel,
//   GetExportTemp,
//   SaveExportTemp
// } from '@/api/Excel'
export default {
  components: {
    draggable
  },
  props: {
    // table查询字段
    queryField: {
      type: Object,
      default() {
        return {};
      }
    },
    // 导出配置
    exportConfig: {
      type: Object,
      default() {
        return {};
      }
    },
    // 已选中的数据
    /**@type { { selected:[], all:[] } } */
    selections: {
      type: Object,
      default() {
        return {
          selected: [],
          all: []
        };
      }
    },
    // 选择导出的key
    selectionsKey: {
      type: String
    },
    // 弹窗是否可见
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      innerVisible: false,
      selectTemplate: "",
      // 是否只导出已选择的数据
      isSelected: false,
      // 是否只导出当页数据
      isPartial: false,
      // 自定义文件名
      fileName: "",
      // 表格字段列表
      columnList: [],
      initColumnList: [],
      templateList: [],
      templateName: "",
      needChangeTemplate: "",
      overflowTemplateNum: 10,
      state: "",
      exportKey: "",
      loading: false
    };
  },
  computed: {
    allSelected() {
      return (
        this.columnList.filter(i => i.Picked).length === this.columnList.length
      );
    },
    canDelete() {
      if (!this.selectTemplate) return false;
      const idx = this.renderTemplateList.custom.findIndex(
        i => i.value === this.selectTemplate
      );
      return idx !== -1;
    },
    templateIsOverflow() {
      return (
        this.templateList.filter(el => el.tempType !== 1).length >
        this.overflowTemplateNum
      );
    },
    renderTemplateList() {
      const templateObj = {
        custom: [],
        internal: []
      };
      this.templateList.forEach(element => {
        if (element.tempType === 1) {
          templateObj.internal.push(element);
        } else {
          templateObj.custom.push(element);
        }
      });
      return templateObj;
    },
    isDataKeyArray() {
      return Array.isArray(this.dataKey);
    }
  },
  watch: {
    isPartial(val) {
      if (val) {
        this.isSelected = false;
      }
    },
    isSelected(val) {
      if (val) {
        this.isPartial = false;
      }
    },
    innerVisible(newVal) {
      if (newVal) {
        const template = this.templateList.find(
          el => el.value === this.selectTemplate
        );
        if (template && template.tempType !== 1) {
          this.needChangeTemplate = this.selectTemplate;
        }
      } else {
        this.templateName = "";
        this.needChangeTemplate = "";
      }
    }
  },
  created() {
    this.exportKey = this.handleDataKey();
    this.initExportFeilds();
    this.initExportTemp();
  },
  methods: {
    handleChangeExportKey() {
      this.initExportFeilds();
      this.initExportTemp();
    },
    // 删除模板
    handleDelTemplate() {
      this.$sxConfirm("还没接接口！", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        // TODO: 对接接口
        this.selectTemplate = "";
        this.handleReset();
        this.initExportTemp();
      });
    },
    // 重置字段
    handleReset() {
      this.columnList = deepCopy(this.initColumnList);
    },
    // 全选/全不选 字段
    handleSelectAll() {
      this.columnList = deepCopy(this.columnList).map(items => {
        items.Picked = !this.allSelected;
        return items;
      });
    },
    // 选中输入建议
    handleSelect(item) {
      this.columnList.find(i => i.ID === item.id).Picked = true;
    },
    // 输入建议
    querySearch(queryString, cb) {
      var restaurants = this.columnList;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(
        results.map(i => {
          return {
            value: i.ColName,
            id: i.ID
          };
        })
      );
    },
    createFilter(queryString) {
      return restaurant => {
        return PinyinMatch.match(restaurant.ColName, queryString);
      };
    },
    //中文首拼排序
    sortByPinYin(array) {
      return array.sort((a, b) =>
        a.ColName.localeCompare(b.ColName, "zh-Hans-CN", {
          sensitivity: "accent"
        })
      );
    },
    // 选中模板事件
    OnChangeTemplate(value) {
      this.columnList = this.templateList.find(
        el => el.value === value
      ).template;
    },
    // 修改导出模板
    changeTemplate() {
      // const templateName = this.templateName.trim()
      // const needChangeTemplate = this.needChangeTemplate
      // const params = {
      //   TempJson: JSON.stringify(this.columnList),
      //   TableKey: this.exportKey
      // }
      // const createNewTemplate = templateName !== '' && needChangeTemplate === ''
      // const renameTemplate = templateName !== '' && needChangeTemplate !== ''
      // const updateTemplate = templateName === '' && needChangeTemplate !== ''
      // const emptyTemplate = templateName === '' && needChangeTemplate === ''
      // const oldTemplateName = this.templateList.find(
      //   el => el.value === needChangeTemplate
      // )
      // switch (true) {
      //   // 新建模板
      //   case createNewTemplate:
      //     if (this.templateIsOverflow) {
      //       return this.$sxMessage({
      //         message: '模版数量已达上限，请选择要替换的模板',
      //         type: 'error'
      //       })
      //     }
      //     params.Name = templateName
      //     break
      //   // 重命名模板
      //   case renameTemplate:
      //     params.Name = templateName
      //     params.NameOld = oldTemplateName.label
      //     break
      //   // 更新模板
      //   case updateTemplate:
      //     params.NameOld = oldTemplateName.label
      //     break
      //   // 模板名称为空，触发警告
      //   case emptyTemplate:
      //     return this.$sxMessage({
      //       message: '请选择要替换的模板并填写新的模板名称',
      //       type: 'error'
      //     })
      // }
      // SaveExportTemp(params).then(res => {
      //   this.innerVisible = false
      //   if (res.success) {
      //     this._handleExport()
      //   }
      //   this.initExportTemp()
      // })
    },
    handleDataKey() {
      // if (Array.isArray(this.dataKey)) {
      //   return this.dataKey[0].value
      // } else {
      //   return this.dataKey
      // }
      return "";
    },
    // 初始化导出字段
    async initExportFeilds() {
      // this.loading = true
      // const { success, data } = await GetExportFeilds({
      //   TableKey: this.exportKey
      // })
      // this.loading = false
      // if (success) {
      //   this.columnList = data.EntityList
      //   this.initColumnList = deepCopy(data.EntityList)
      // }
    },
    // 初始化导出模板
    initExportTemp() {
      // this.selectTemplate = ''
      // GetExportTemp({ TableKey: this.exportKey }).then(res => {
      //   this.overflowTemplateNum = res.data.templateMaxNum || 0
      //   this.templateList = res.data.templateList.map(items => {
      //     return {
      //       label: items.Name,
      //       tempType: items.TempType,
      //       value: items.ExcelExportTemplateId,
      //       template: JSON.parse(items.TempJson)
      //     }
      //   })
      // })
    },
    // 处理选中事件
    _onClickColumnCard(column) {
      this.$set(column, "Picked", !column.Picked);
    },
    // 如果没有勾选仅导出当页数据时，把分页的参数给去除
    fieldPartialData() {
      const queryField = deepCopy(this.queryField);
      delete queryField.PageIndex;
      delete queryField.PageSize;
      return queryField;
    },
    // 处理表格数据
    fieldSelectionData() {
      const queryField = deepCopy(this.queryField);
      let exportTableData = [];
      if (this.selectionsKey) {
        if (this.isSelected) {
          exportTableData = this.selections.selected;
        } else if (this.isPartial) {
          exportTableData = this.selections.all;
        }
      }
      if (exportTableData.length === 0) return queryField;

      queryField.ExportNos = exportTableData
        .map(i =>
          // 导出的 selectKey 如果需要多个字段拼接的话，传入时用 , 隔开，参考 src/pages/DepositMangae 页面的表格传参
          this.selectionsKey
            .split(",")
            .map(key => i[key])
            .join("|")
        )
        .join(",");
      return queryField;
    },
    // 导出并保存按钮事件
    _handleSave() {
      this.innerVisible = true;
    },
    /** 导出按钮操作 */
    _handleExport() {
      let param = {};
      if (this.isSelected) {
        param = {
          [this.exportConfig.key]: this.selections.selected
            .map(i => i[this.exportConfig.value])
            .filter(i => !isNull(i) && typeof(i) != "undefined")
            .join(",")
        };
      }
      if (this.isPartial) {
        param = this.queryField;
      }
      this.downloadExport(param);
    },
    downloadExport(param) {
      this.download(
        this.exportConfig.url,
        param,
        `${this.fileName}_${new Date().getTime()}.xlsx`
      );
    },
    handleDialogClose() {
      this.$emit("update:visible", false);
    }
  }
};
</script>

<style scoped lang="scss">
.sxTableExport {
  // 因为IE不支持display:grid; 此代码是为了兼容IE10以上的布局
  @media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
    /* IE10+ CSS styles go here */
    &__columnList {
      display: flex;
      flex-wrap: wrap;
    }
    &__columnPane {
      margin: 10px;
    }
  }
  &__newTemplateInfo {
    &:first-child {
      margin-bottom: 10px;
    }
    label {
      margin-right: 10px;
      font-weight: 600;
    }
  }
  &__saveTemplate {
    /deep/ .el-dialog__body {
      padding-bottom: 0;
    }
  }
  &__changeTemplate {
    margin: 15px 0;
  }
  &__alert {
    margin-top: 10px;
  }
  &__template {
    display: flex;
    justify-content: space-between;
    margin-top: 20px;
    label {
      margin-right: 10px;
    }
  }

  &__selectGroup {
    display: flex;
    &_pane {
      margin-right: 10px;
      &:first-child {
        /deep/ .el-select {
          width: 120px;
        }
      }
    }
  }

  &__toolBtn {
    margin-left: 10px;
  }

  &__setting {
    margin-top: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  &__columnList {
    display: grid;
    justify-content: space-between;
    grid-template-columns: repeat(auto-fill, 100px);
    grid-gap: 10px;
    margin-top: 20px;
  }
  &__columnPane {
    position: relative;
    width: 100px;
    height: 40px;
    border: 1px solid #ebeef5;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.1);
    overflow: hidden;
    &-active {
      border-color: #13ce679d;
    }
    &-ghost {
      opacity: 0.5;
    }
    span {
      user-select: none;
    }
  }
  &__columnCard {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    padding: 5px;
    box-sizing: border-box;
    span {
      font-size: 12px;
      transform: scale(0.95);
    }
  }
  &__icon {
    display: none;
    position: absolute;
    top: -1px;
    right: -12px;
    width: 36px;
    height: 16px;
    background: #13ce66;
    transform: rotate(45deg);
    box-shadow: 0 1px 1px #ccc;
    text-align: center;
    &-active {
      display: block;
    }
    i {
      transform: rotate(-45deg);
      font-size: 12px;
      color: #fff;
    }
  }
  &__footer {
    button {
      &:last-child {
        margin-left: 10px;
      }
    }
  }
}
</style>
